package com.atguigu.edu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.app.BaseApp;
import com.atguigu.edu.bean.TradePaymentWindowBean;
import com.atguigu.edu.common.Constant;
import com.atguigu.edu.util.AtguiguUtil;
import com.atguigu.edu.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws_09_TradePaymentSucWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_09_TradePaymentSucWindow().init(
                4009,
                2,
                "Dws_09_TradePaymentSucWindow",
                Constant.TOPIC_DWD_TRADE_PAY_DETAIL_SUC
        );
    }

    @Override
    public void handle(StreamExecutionEnvironment ev, DataStreamSource<String> stream) {
        stream
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((obj, ts) -> obj.getLong("ts") * 1000)
                                .withIdleness(Duration.ofSeconds(6))
                )
                .keyBy(obj -> obj.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradePaymentWindowBean>() {

                    private ValueState<String> lastPayDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastPayDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastPayDate", String.class));
                    }

                    @Override
                    public void processElement(JSONObject obj,
                                               Context ctx,
                                               Collector<TradePaymentWindowBean> out) throws Exception {
                        long ts = obj.getLong("ts") * 1000;
                        String today = AtguiguUtil.tsToDate(ts);

                        // 支付成功独立用户数
                        Long paymentSucUniqueUserCount = 0L;
                        // 支付成功新用户数
                        Long paymentSucNewUserCount = 0L;

                        String lastPayDate = lastPayDateState.value();

                        if (!today.equals(lastPayDate)) {
                            // 今天第一次
                            paymentSucUniqueUserCount = 1L;
                            lastPayDateState.update(today);
                            // 如果是今天第一次, 判断是否这个用户的在电商首次支付
                            if (lastPayDate == null) { // 是首次
                                paymentSucNewUserCount = 1L;
                            }
                        }

                        if (paymentSucUniqueUserCount == 1) {
                            out.collect(new TradePaymentWindowBean(
                                    "", "",
                                    paymentSucUniqueUserCount, paymentSucNewUserCount,
                                    ts
                            ));
                        }

                    }
                })
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<TradePaymentWindowBean>() {
                            @Override
                            public TradePaymentWindowBean reduce(TradePaymentWindowBean value1,
                                                                 TradePaymentWindowBean value2) throws Exception {
                                value1.setPaymentSucNewUserCount(value1.getPaymentSucNewUserCount() + value2.getPaymentSucNewUserCount());
                                value1.setPaymentSucUniqueUserCount(value1.getPaymentSucUniqueUserCount() + value2.getPaymentSucUniqueUserCount());
                                ;
                                return value1;
                            }
                        },
                        new AllWindowFunction<TradePaymentWindowBean, TradePaymentWindowBean, TimeWindow>() {
                            @Override
                            public void apply(TimeWindow window,
                                              Iterable<TradePaymentWindowBean> values,
                                              Collector<TradePaymentWindowBean> out) throws Exception {
                                TradePaymentWindowBean bean = values.iterator().next();
                                bean.setStt(AtguiguUtil.tsToDateTime(window.getStart()));
                                bean.setEdt(AtguiguUtil.tsToDateTime(window.getEnd()));

                                bean.setTs(System.currentTimeMillis());

                                out.collect(bean);
                            }
                        }
                )
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_payment_suc_window", TradePaymentWindowBean.class));
    }
}
